let overtimer_auto_close_loading_timer = null; //超时自动关闭。
let loading_close = false;
const NameSpace = {
	user_token: "uni_id_token", //此token不可修改。因为uni-id要用它。前端使用ClientB方式操作时. uniCloud框架底层，会自动在callfunction时传递uni-id的token
	user_expired: "uni_id_token_expired",
	user_info: "uni-cloud-login-user-info",
}
export default {
	/**
	 * 延时。在async 函数中。await utils.delay(1000);
	 * @param {Object} second 秒。
	 */
	// api.getFileServerToken实现如下
	async getFileServerToken(){
			let res = await this.request("admin/upload/getToken");
			let uploadToken = res.data;
			uni.setStorageSync("upload_token", uploadToken );
			return res.data;
	},
	async getCustomerFileServerToken(){
			let res = await this.request("v2/client/upload/getToken");
			let uploadToken = res.data;
			uni.setStorageSync("upload_token", uploadToken );
			return res.data;
	},
	delay(second) {
		return new Promise((execute) => {
			setTimeout(() => {
				execute();
			}, second);
		});
	},
	loading(msg = "正在加载请稍后...") {
		uni.showLoading({
			title: msg
		});
		loading_close = false;
		if (overtimer_auto_close_loading_timer == null) {
			let _this = this;
			overtimer_auto_close_loading_timer = setTimeout(() => {
				clearTimeout(overtimer_auto_close_loading_timer);
				overtimer_auto_close_loading_timer = null;
				if (loading_close == false) {
					//如果还没关闭。说明可能网络调用超时。还没来得及调用hideLoading(),此时要记得关闭掉。
					_this.hideLoading();
				}
			}, 5000);
		}
	},
	hasValue(value){
		if( value == undefined  )return false;
		if( value == null )return false;
		if( typeof value == "undefined"  )return false;
		if( typeof value =="string" && value.length == 0 )return false;
		return true;
		
	},
	isEmpty(value){ //
		if(!value)return true;
		if(value.length == 0 )return true;
		return false;
	},
	hideLoading() {
		loading_close = true;
		try {
			uni.hideLoading();
		} catch (e) {}
		if (overtimer_auto_close_loading_timer != null) {
			clearTimeout(overtimer_auto_close_loading_timer);
			overtimer_auto_close_loading_timer = null;
		}
	},
	tips(msg) {
		let _this = this;
		uni.showToast({
			icon: "none",
			title: msg,
			complete() {
				_this.hideLoading();
			}
		})
	},
	alert(msg, callback , title) {
		uni.showModal({
			title: title ? title : "提示",
			content: msg,
			showCancel: false,
			success() {
				if (typeof callback == "function") {
					callback();
				}
			}
		})
	},
	confirm(callback, msg, title) {
		uni.showModal({
			title: title ? title : "提示",
			content: msg,
			success(res) {
				if (res.confirm) {
					callback();
				}
			}
		})
	},

	async request(url, data, loadingtips = "请稍候...", ignoreError) {
		if (!url) return this.alert("请求地址错误：" + url);
		this.loading(loadingtips);
		let res;
		try {
			res = await uniCloud.callFunction({
				name: "controller",
				data: {
					url,
					param: data
				} //token:utils.getToken() 以后再也不用了。uniCloud自带了。
			});
		} catch (e) { //编译错误。
			this.alert(url + " Runtime Error : " + e.message);
			throw e;
		} finally {
			this.hideLoading();
		}


		//可以统一弹框。
		let {
			result
		} = res;
		let {
			code,
			message
		} = result;

		if (code < 0 && !ignoreError) {
			this.alert(message);
			if (code == -666 || code == 401 || code == 1600) {
				localStorage.removeItem("uni_id_token")
				localStorage.removeItem("uni-cloud-login-user-info")
				uni.navigateTo({
					url: "/pages/login/login"
				})
			}
			throw new Error(message); //抛出异常阻止后续执行。
		}
		return result;
	},

	//不弹窗
	async unlorequest(url, data, ignoreError) {
		if (!url) return this.alert("请求地址错误：" + url);
		let res = await uniCloud.callFunction({
			name: "controller",
			data: {
				url,
				param: data
			}
		});
		let {
			result
		} = res;
		return result;
	},
	/**升序排序 + 优化次数 + 快速
	 * @param {Object} list 数组
	 * @param {Object} k 待比较的字段。
	 */
	sort(list, k) {
		let bigger_item = list[0];
		let exchange = false;
		for (let i = 0; i < list.length - 1; i++) {
			exchange = false;
			for (let j = 0; j < list.length - 1 - i; j++) {
				if (list[j][k] > list[j + 1][k]) {
					//交换位置。大的往右边挪动。
					let item = list[j];
					list[j] = list[j + 1];
					list[j + 1] = item;
					exchange = true;
				}
			}
			//增加性能。
			if (!exchange) {
				break;
			}
		}
	},
	sortNum(list) {
		let bigger_item = list[0];
		let exchange = false;
		for (let i = 0; i < list.length - 1; i++) {
			exchange = false;
			for (let j = 0; j < list.length - 1 - i; j++) {
				if (list[j] > list[j + 1]) {
					//交换位置。大的往右边挪动。
					let item = list[j];
					list[j] = list[j + 1];
					list[j + 1] = item;
					exchange = true;
				}
			}
			//增加性能。
			if (!exchange) {
				break;
			}
		}
	},
	uploadImgs(callback, progress,count = 9) { //多张上传。
		let _this = this;
		uni.chooseImage({
			sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
			sourceType: ['camera', 'album'],
			count: count,
			success(res) {
				if (res.tempFilePaths.length > 0) {
					  res.tempFilePaths.forEach((filePath,index)=>{
						  _this.startUpload(filePath, callback, progress,index+1,".jpg")
					  });
				}
			}
		});
	},
	uploadImage(callback, count = 5) {
		uni.chooseImage({
			sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
			sourceType: ['camera', 'album'],
			count,
			success: (res) => {
				let tempFilePaths = res.tempFilePaths
				let timestamp = Date.now()
				tempFilePaths.forEach((filePath, index) => {
					let suffix = filePath.substr(filePath.lastIndexOf('.')) //后缀名
					let cloudPath = `image/${timestamp+index}${suffix}`
					uniCloud.uploadFile({
						filePath,
						cloudPath,
						onUploadProgress: (progressRes) => {
							var percentCompleted = Math.round(
								(progressRes.loaded * 100) / progressRes.total
							);
							this.tips(percentCompleted + "%");
						},
						success: (res) => {
							uniCloud.getTempFileURL({
								fileList: [res.fileID]
							}).then(rs => {
								callback && callback(rs.fileList[0]
								.tempFileURL);
							});
						},
						fail: (error) => {
							this.alert(`第${index}张发送失败!`);
						}
					});
				})
			}
		});
	},
	
	uploadVideo(callback, progress) { //单张上传。
		let _this = this;
		uni.chooseVideo({
			count: 1,
			sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
			sourceType: ['camera', 'album'],
			success: function(res) {
				let filePath = res.tempFilePath;
				_this.startUpload(filePath, callback, progress,1, ".mp4");
			}
		});
	},

	//获取相片
	async choosePhoto() {
		return new Promise((resolve, reject) => {
			uni.showActionSheet({
				title: '选择相片',
				itemList: ['拍照', '相册'],
				success: (tapRes) => {
					if (!tapRes.tapIndex) {
						this.takePhoto((filePath) => {
							resolve(filePath)
						})
					} else {
						uni.chooseImage({
							count: 1,
							sizeType: ['original'],
							sourceType: ['album'],
							complete: (res) => {
								if (res.tempFilePaths.length) {
									let filePath = res.tempFilePaths[0]
									resolve(filePath)
								} else {
									reject("")
								}
							}
						})
					}
				},
				fail: (e) => {
					console.log("fail", e)
					reject("")
				}
			})
		})
	},
	
	takePhoto(callback) {
		if (typeof callback !== 'function') {
			throw new Error('必须传入回调方法')
		}
		// #ifdef APP
		const dcCamera = uni.requireNativePlugin('DCloud-Camera')
		dcCamera.takePhoto((res) => {
			if (res.imagePaths) {
				callback(res.imagePaths)
			} else {
				callback('')
			}
		})
		// #endif
		// #ifdef MP-WEIXIN 
		uni.navigateTo({
			url: '/pages/takePhoto/takePhoto',
			events: {
				onCameraBack: (res) => {
					if (res.imagePaths) {
						callback(res.imagePaths)
					} else {
						callback('')
					}
				}
			}
		})
		// #endif
		// #ifdef H5 
		uni.navigateTo({
			url: '/pages/check-face/select-face-picture',
			events: {
				onCameraBack: (res) => {
					if (res.imagePaths) {
						callback(res.imagePaths)
					} else {
						callback('')
					}
				}
			}
		})
		// #endif
	},

	/**
	 * @param STSToken 阿里云临时上传凭证，云函数返回
	 * @param filePath 本地文件路径
	 */
	uploadFile(STSToken, filePath, callback, index = 1) {
		if (typeof callback !== 'function') {
			throw new Error('必须传入回调方法')
		}

		let fileType = "image"
		let suffix = filePath.substr(filePath.lastIndexOf('.'));
		suffix = suffix.toLowerCase()
		switch (suffix) {
			case ".jpg":
			case ".png":
			case ".gif":
				fileType = "image";
				break;
			case ".mp4":
				fileType = "video";
				break;
			case ".mp3":
				fileType = "audio";
				break;
			default:
				fileType = "other";
				break;
		}

		let key = fileType + "/" + new Date().getTime()+""+index + suffix; //后缀名

		this.loading("正在上传第" + index + "项");
		uni.uploadFile({
			url: STSToken.url,
			filePath,
			fileType,
			name: 'file',
			formData: {
				name: key,
				key: key,
				policy: STSToken.policy,
				OSSAccessKeyId: STSToken.AccessKeyId,
				signature: STSToken.signature,
				success_action_status: '200', // 让服务端返回200,不然，默认会返回204
				"x-oss-security-token": STSToken.SecurityToken
			},
			complete: (res) => {
				if (res.statusCode == 200) {
					callback(key,index - 1 );//index 返回时从0开始计算。
				}
			}
		})
	},

	uploadFiles(STSToken, filePaths, callback) {
		filePaths.forEach((filePath, index) => {
			this.uploadFile(STSToken, filePath, callback, index + 1)
		})
	},
	
	startUpload(filePath, callback, progress,index = 1,affter_fix=".jpg") {
		let _this = this;
		this.loading("正在上传第"+index+"项");
		uniCloud.uploadFile({
			filePath: filePath,
			cloudPath: Date.now() + '/' + Date.now() + index+affter_fix ,  
			onUploadProgress: function(progressEvent) {
				var percentCompleted = Math.round(
					(progressEvent.loaded * 100) / progressEvent.total
				);
				_this.tips("第"+(index)+"项已完成" + percentCompleted + "%");
				progress && progress(percentCompleted);
			},
			success(res) {
				_this.tips("第"+(index)+"项上传完成！");
				uniCloud.getTempFileURL({
						fileList: [res.fileID]
				})
				.then( rs => {
					callback && callback(rs.fileList[0].tempFileURL);
				});
			},
			fail(res) {
				_this.alert("第"+(index)+"项上传失败!");
			}
		});
	},
}
